slint::include_modules!();
use hyper_net::prelude::*;
use hyper_net::prelude::*;
use log::{debug, error, info, log_enabled, Level};
use slint::{Timer, TimerMode};
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::time::Instant;
use tokio::runtime;

fn main() -> Result<(), reqwest::Error> {
    env_logger::init();
    let app = Hyper::new().unwrap();
    let source = app.get_image_source();
    let data = source_to_image(&source, "filename.png");

    let mut cost_time: f32 = 0.0f32;
    app.on_request_data(move |url, data| {
        debug!("mesg = {}", &data);
        let d = serde_json::from_str(&data).expect("解析字符串失败");
        debug!("this is a debug {:?}", d);
        let runtime = runtime::Runtime::new().unwrap();
        let binding = url.to_string();
        let t1 = Instant::now();
        let post_request_future = post_request(binding.as_str(), d);
        let resp = runtime.block_on(post_request_future);
        let t2 = Instant::now();
        cost_time = (t2 - t1).as_secs_f32();
        debug!("cost time:{}", cost_time);
        if let Ok(res) = resp {
            result_process(res).response.into()
        } else {
            "no message".into()
        }
    });
    app.set_cost_time(cost_time);
    debug!("data = {} cost time:{}", cost_time, app.get_cost_time());

    app.set_image_data(vec_to_image(data));
    let timer = Timer::default();
    {
        let main_window_weak = app.as_weak();
        timer.start(
            TimerMode::Repeated,
            std::time::Duration::from_millis(10),
            move || {
                let main_window = main_window_weak.unwrap();
                main_window.invoke_tick(10);
            },
        );
    }
    app.as_weak().unwrap().run().unwrap();
    Ok(())
}
